<template>
  <div class="month-panel cell-list">
    <div class="cell-item" :key="item.toString()" v-for="item in monthList">
      <div :class="getClass(item)" @click="pickMonth(item)">
        <span>{{ item.format("M月") }}</span>
      </div>
    </div>
  </div>
</template>

<script>
import { computed, inject, ref } from "vue";
import dayjs from "dayjs";
export default {
  name: "month-panel",
  setup() {
    // 接收父组件传值
    const [date, setDate] = inject("date", [ref(new Date()), (v) => v]);
    const [displayMode, setDisplayMode] = inject("displayMode", [
      ref("date"),
      (v) => v,
    ]);
    // 月点击设置时间模式和时间
    const pickMonth = (item) => {
      setDate(item.toDate());
      setDisplayMode("date");
    };
    // 生成日历表
    const monthList = computed(() => {
      // 本年的第一个月
      const month0 = dayjs(date.value).month(0);
      // 返回一个从当前第一个月开始后面的16个月
      return Array(16)
        .fill(0)
        .map((n, i) => month0.add(i, "month"));
    });
    // 当前时间样式
    const getClass = (item) => {
      return [
        "month-cell",
        item.month() === dayjs(date.value).month() && " current-month ",
        item.year() === dayjs(date.value).year() && " current-year ",
      ].join(" ");
    };

    return {
      monthList,
      getClass,
      pickMonth,
    };
  },
};
</script>

<style lang="less" rel="stylesheet/less">
.month-panel {
  .cell-item {
    width: 25%;
    padding: 2px;
  }
  .month-cell {
    cursor: pointer;
    border: 2px solid #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 73.5px;
    color: #999;
    &.current-year {
      color: #fff;
    }
  }
}
</style>
